import { useUpdate } from 'ahooks';
import { message } from 'antd';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { useContextSelector } from 'use-context-selector';

import chatService from '@/api/services/chatService';
import useWindowWidth from '@/hooks/event/use-window-width';
import MessageSendInputHome from '@/pages/app-qa/components/homepage/components/MessageSendInputHome';
import { resetCookie } from '@/pages/auth/authUtils';
import { useRouter } from '@/router/hooks';
import { useIsDeepMode, useIsOnlineMode } from '@/store/chatStore';
import { useConfig, useAppInfo } from '@/store/configStore';
import { useMetahumanStore } from '@/store/metahumanStore';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { useShareChatStore } from '@/store/shareStore';
import userStore from '@/store/userStore';
import { ChatEventType } from '@/types/chat';
import { ResultEnum } from '@/types/enum';

import { ChatContext } from '../context';
import {
  SseResponseEventEnum,
  Quote,
  ToolModuleResponseItemType,
  VariableInputEnum,
} from '../tools/constants';
import { streamFetch, StreamResponseType } from '../tools/fetch';
import { getNanoid } from '../tools/tools';

import MessageList from './MessageList';
import MetaMessageList from './MetaMessageList';

import type { StartChatFnProps } from '../tools/constants';

interface Message {
  text: string;
  isUser: boolean;
  loading?: boolean;
  loadingText?: string;
  chatId?: string;
  dataId?: string;
  ts?: number;
  appName?: string;
  appLogo?: string;
  appId?: string;
  shareId?: string;
  appType?: string;
  quote?: Quote[];
  isSurvey?: boolean;
  isTextGenerate?: boolean;
  toolJson?: Record<string, ToolModuleResponseItemType>;
  interactive?: any;
  thinkList?: {
    title: string;
    description: string;
    status: string;
  }[];
}

interface GuessQuestion {
  id: string;
  content: string;
}

interface ChatBoxProps {
  initChatId: string;
  initialQuestion?: string;
  initialMessages?: Message[]; // Define the prop for initial messages as optional
  isTest: boolean;
  onStartChat?: (e: StartChatFnProps) => Promise<
    StreamResponseType & {
      isNewChat?: boolean;
    }
  >;
  onUpdateHistory?: () => void;
  workflowDebug?: boolean;
  initAppId?: string;
  initShareId?: string;
}

const ChatBox: React.FC<ChatBoxProps> = ({
  isTest,
  initialQuestion = '',
  initialMessages = [],
  initChatId = '',
  onStartChat,
  onUpdateHistory,
  workflowDebug = false,
  initAppId = '',
  initShareId = '',
}) => {
  const update = useUpdate();
  const { title } = useConfig();
  const isDeepMode = useIsDeepMode();
  const isOnlineMode = useIsOnlineMode();
  const [messages, setMessages] = useState<Message[]>(initialMessages);
  const [chatNanoId, setChatNanoId] = useState('');
  const [isMessageSend, setIsMessageSend] = useState(false);
  const { isPc } = useWindowWidth();
  const [messageApi, contextHolder] = message.useMessage();
  const [voice, setVoice] = useState(false);
  const [isTextGenerate, setIsTextGenerate] = useState(false);
  const [guessQuestions, setGuessQuestions] = useState<GuessQuestion[]>([]);

  const { isMuteToggle, setIsMuted, isMuted, setIsMuteToggle } = useMetahumanStore();

  const { virtualAvatarEnabled, permissionConfig, sessionId, metahumanUrl } = useMetahumanStore();

  type ThinkFilterMapType = {
    [key: string]: string;
  };

  const thinkFilterMap: ThinkFilterMapType = {
    RAG对话: '大模型对话',
    知识库搜索: '知识库搜索',
    安全内容审核: '内容安全审核',
    内容安全审核: '内容安全审核',
    问题优化: '问题理解',
    问题分类: '问题理解',
  };

  const appInfoInitialize = useAppInfo();
  const router = useRouter();

  const currentMessageRef = useRef('');
  const thinkListcurrentMessageRef = useRef([]);
  const { localUId } = useShareChatStore();

  const { event$, setChatId } = useContextSelector(ChatContext, (s) => s);

  const textAreaRef = useRef<HTMLTextAreaElement | null>(null);
  const customVariables = {};
  const appType = 'advanced';

  const {
    voiceEnabled,
    shareId,
    configurations: configurationsBase,
    variables,
    workflow,
    fusionAppId,
    isInOrchestrationPage,
    userSelectVariables,
    appDetail,
    subAppDetail,
  } = useOrchestrationStore();
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const id = queryParams.get('id') || queryParams.get('appId') || initAppId || '';
  const sid = queryParams.get('sid') || queryParams.get('shareId') || shareId || initShareId || '';
  const configurations = subAppDetail ? subAppDetail?.configurations : configurationsBase;
  const guessQuestionConfig = configurations?.find(
    (config: any) => config.name === 'guess_you_want2ask',
  );
  const isGuessQuestion =
    guessQuestionConfig?.default_value === '1' ||
    guessQuestionConfig?.default_value === true ||
    (workflow && workflow?.chatConfig.questionGuide);

  const internetSearchConfig = configurations?.find(
    (config: any) => config.name === 'internet_search',
  );
  const isInternetSearch =
    internetSearchConfig?.default_value === '1' || internetSearchConfig?.default_value === true;

  const quoteConfig = configurations?.find((config: any) => config.name === 'quote_enable');
  const isQuote = quoteConfig?.default_value === '1' || quoteConfig?.default_value === true;

  const deepThinkConfig = configurations?.find((config: any) => config.name === 'deep_think');
  const isDeepThink =
    deepThinkConfig?.default_value === '1' || deepThinkConfig?.default_value === true;

  const isAnswerEvent = (event: SseResponseEventEnum) =>
    event === SseResponseEventEnum.answer || event === SseResponseEventEnum.fastAnswer;

  const isToolCallEvent = (event: SseResponseEventEnum) =>
    event === SseResponseEventEnum.toolCall ||
    event === SseResponseEventEnum.toolParamsDescription ||
    event === SseResponseEventEnum.toolParams ||
    event === SseResponseEventEnum.toolResponse;

  const isInteractiveEvent = (event: SseResponseEventEnum) =>
    event === SseResponseEventEnum.interactive;

  useEffect(() => {
    initialQuestion && handleSend(initialQuestion);
  }, [initialQuestion]);

  const startChat = useCallback(
    async ({
      messages,
      controller,
      chatId,
      generatingMessage,
      variables,
      responseChatItemId,
    }: StartChatFnProps) => {
      // if (!id) {
      //   messageApi.error('未获取到应用ID');
      //   return;
      // }
      // if (!sid) {
      //   messageApi.error('未获取到 shareID');
      //   return;
      // }

      // const histories = messages.slice(-1);
      const histories = messages;

      const { responseText, responseData } = await streamFetch({
        url: isTest
          ? '/openapi/v1/chat/annotation/test'
          : isInOrchestrationPage
          ? '/openapi/v1/chat/chatTest'
          : '/openapi/v1/chat/completions',
        // url: isTest ? '/openapi/v1/chat/annotation/test' : '/openapi/v1/chat/completions',
        // url: '/openapi/v1/chat/chatTest',
        // url: (isTest || isInOrchestrationPage) ? '/openapi/v1/chat/annotation/test' : '/openapi/v1/chat/completions',
        data: {
          appName: subAppDetail?.app_name ? subAppDetail?.app_name : appDetail?.app_name,
          messages: histories,
          ...(appDetail?.model && !subAppDetail && { config: appDetail.model }),
          variables: {
            isPc,
            r1_enabled: isDeepThink && isDeepMode == true ? '1' : '0',
            search_enabled: isInternetSearch && isOnlineMode == true ? '1' : '0',
            industry: appInfoInitialize?.industry_type ? appInfoInitialize?.industry_type : '',
            app: title,
            ...configurations.reduce((acc: Record<string, string>, config) => {
              acc[config.name] = String(
                config.default_value === true
                  ? '1'
                  : config.default_value === false
                  ? '0'
                  : config.default_value,
              );
              return acc;
            }, {}),
            ...variables,
            ...customVariables,
          },
          appId: fusionAppId || id,
          shareId: subAppDetail?.share_id ? subAppDetail?.share_id : sid,
          chatId,
          responseChatItemId,
          appType,
          outLinkUid: localUId,
          fusionAppId: id,
          mhUrl: metahumanUrl,
          mhSessionId: sessionId,
        },
        onMessage: generatingMessage,
        abortCtrl: controller,
      });

      // 触发历史记录的更新
      onUpdateHistory && onUpdateHistory();
      return { responseText, responseData };
    },

    [customVariables, chatNanoId],
  );

  const [startChatProps, setStartChatProps] = useState<StartChatFnProps | null>(null);


  useEffect(() => {
    if (!startChatProps?.controller) return;
    return () => {
      // 失效时调用 abort
      startChatProps.controller.abort();
    };
  }, [startChatProps?.controller]);


  const handleInterrupt = async () => {
    if (startChatProps?.controller) {
      startChatProps.controller.abort();
      setIsMessageSend(false);
      setMessages((prevMessages) => {
        const updatedMessages = [...prevMessages];
        const lastIndex = updatedMessages.length - 1;
        if (lastIndex >= 0 && updatedMessages[lastIndex].loading) {
          updatedMessages[lastIndex] = { ...updatedMessages[lastIndex], loading: false };
        }
        return updatedMessages;
      });
      messageApi.info('回答已取消');
    }
  };

  const generateGuessQuestions = (messagesHistory: Message[]) => {
    // 转换当前消息列表为API所需的格式
    console.log(messagesHistory);
    setGuessQuestions([]);

    const chatMessages = messagesHistory.map((msg) => ({
      role: msg.isUser ? ('user' as const) : ('assistant' as const),
      content: msg.text,
    }));

    // 调用API生成猜你想问的问题
    chatService
      .createQuestionGuide({
        messages: chatMessages,
      })
      .then((response) => {
        console.log('response============', response);
        if (
          response &&
          Array.isArray(response) &&
          response.every((item) => typeof item === 'string')
        ) {
          const newGuessQuestions: GuessQuestion[] = response.map((item, index) => ({
            id: String(index + 1),
            content: item.toString(),
          }));

          // 更新猜你想问的问题列表
          if (newGuessQuestions.length > 0) {
            setGuessQuestions(newGuessQuestions);
          }
        } else {
          // 如果API调用失败或返回为空，使用默认问题
          setGuessQuestions([]);
        }
      })
      .catch((error) => {
        console.error('获取猜你想问失败:', error);
        // 发生错误时使用默认问题
        setGuessQuestions([]);
      });
  };

  const handleSend = async (question: string | undefined, isUserSelect = false) => {
    if (typeof question !== 'string') {
      return;
    }
    if (isMessageSend) {
      return;
    }
    if (isMessageSend && !question) {
      return;
    }

    if (!chatStarted && subAppDetail) {
      messageApi.warning('基础信息未提交！');
      return;
    }

    const lastMessage = messages?.slice(-1)?.[0];

    if (lastMessage?.interactive && !isUserSelect && !lastMessage?.text) {
      messageApi.warning('参数未提交！');
      return;
    }

    const q = question.trim();

    const completionChatId = initChatId || getNanoid();
    let chatId = '';
    if (!chatNanoId) {
      chatId = completionChatId;
      setChatId(completionChatId);
      setChatNanoId(completionChatId);
    } else {
      chatId = chatNanoId;
    }
    currentMessageRef.current = '';
    thinkListcurrentMessageRef.current = [];

    // 根据 isUserSelect 判断 responseChatId 的取值
    const responseChatId = isUserSelect
      ? messages.length > 0
        ? messages[messages.length - 1].dataId
        : getNanoid(24)
      : getNanoid(24);
    const humanChatId = getNanoid(24);

    const userMessage = {
      text: q,
      isUser: true,
      dataId: humanChatId,
      chatId,
    };

    const role = isUserSelect ? 'assistant' : 'user';

    const assistantMessage = {
      dataId: humanChatId,
      role,
      content: q,
      chatId,
      interactive: messages.length > 0 ? messages[messages.length - 1]?.interactive : '',
    };
    const commitMessage = isUserSelect
      ? workflowDebug
        ? [
            ...messages.slice(0, -1).map((msg) => ({
              content: msg.text,
              interactive: msg?.interactive,
              role: msg.isUser ? 'user' : 'assistant',
              dataId: msg.dataId,
              chatId,
            })),
            assistantMessage,
            {
              content: q,
              role: 'user',
              dataId: humanChatId,
              chatId,
            },
          ]
        : [
            // {
            //   content: messages?.[messages.length - 2]?.text || '',
            //   role: 'user',
            //   dataId: getNanoid(24),
            //   chatId,
            // },
            ...messages.slice(0, -1).map((msg) => ({
              content: msg.text,
              interactive: msg?.interactive,
              role: msg.isUser ? 'user' : 'assistant',
              dataId: msg.dataId,
              chatId,
            })),
            assistantMessage,
            {
              content: q,
              role: 'user',
              dataId: humanChatId,
              chatId,
            },
          ]
      : [
          {
            content: q,
            role,
            dataId: humanChatId,
            chatId,
          },
        ];

    console.log(messages, assistantMessage, commitMessage, 'messages');

    !isUserSelect && setMessages((prevMessages) => [...prevMessages, userMessage]);

    const newStartChatProps: StartChatFnProps = {
      messages: commitMessage,
      controller: new AbortController(),
      chatId,
      responseChatItemId: responseChatId,
      generatingMessage: (message) => {
        if (message.event == SseResponseEventEnum.error) {
        }
        if (message.event == SseResponseEventEnum.flowNodeStatus) {
          const thoughtItem = {
            title: message.name,
            description: '暂无',
            status: 'success',
          };

          let matchedKeyword = null;
          for (const filterItem of Object.keys(thinkFilterMap) as Array<
            keyof typeof thinkFilterMap
          >) {
            // if (thoughtItem.title && thoughtItem.title.startsWith(String(filterItem))) {
            if (thoughtItem.title && thoughtItem.title.includes(String(filterItem))) {
              matchedKeyword = thinkFilterMap[filterItem];
              break;
            }
          }

          if (matchedKeyword) {
            const mappedTitle = matchedKeyword; // 映射为匹配到的关键词

            // 移除已存在的重复条目
            thinkListcurrentMessageRef.current = thinkListcurrentMessageRef.current.filter(
              (item) => item.title !== mappedTitle,
            );

            // 添加新的条目
            thinkListcurrentMessageRef.current.push({ ...thoughtItem, title: mappedTitle });
          }

          setMessages((prevMessages) => {
            const lastMessage = prevMessages[prevMessages.length - 1];

            const newMessage = {
              thinkList: thinkListcurrentMessageRef.current,

              text: currentMessageRef.current,
              isUser: false,
              loading: true,
              chatId,
              dataId: humanChatId,
              loadingText: message.event,
              appType: appDetail?.appType,
              appName: subAppDetail?.app_name ? subAppDetail?.app_name : appDetail?.app_name,
              appLogo: subAppDetail?.app_logo ? subAppDetail?.app_logo : appDetail?.app_logo,
              appId: subAppDetail?.app_id || id,
              shareId: subAppDetail?.share_id || sid,
              toolJson: lastMessage?.toolJson,
            };

            if (
              lastMessage &&
              lastMessage.text === newMessage.text &&
              lastMessage.thinkList == newMessage.thinkList &&
              lastMessage.loadingText === newMessage.loadingText
            ) {
              return prevMessages;
            }

            if (lastMessage && !lastMessage.isUser) {
              return [...prevMessages.slice(0, -1), newMessage];
            }

            return [
              ...prevMessages,
              {
                thinkList: thinkListcurrentMessageRef.current,
                text: currentMessageRef.current,
                isUser: false,
                loading: false,
                chatId,
                dataId: responseChatId,
                loadingText: message.event,
                toolJson: lastMessage?.toolJson,
              },
            ];
          });

          update();
        }
        if (message.event == 'contentViolation') {
          currentMessageRef.current = `${message.text}`;
          setMessages((prevMessages) => {
            const lastMessage = prevMessages[prevMessages.length - 1];

            const newMessage = {
              thinkList: thinkListcurrentMessageRef.current,

              text: currentMessageRef.current,
              isUser: false,
              loading: true,
              chatId,
              dataId: humanChatId,
              loadingText: message.event,
              appType: appDetail?.appType,
              appName: subAppDetail?.app_name ? subAppDetail?.app_name : appDetail?.app_name,
              appLogo: subAppDetail?.app_logo ? subAppDetail?.app_logo : appDetail?.app_logo,
              appId: subAppDetail?.app_id || id,
              shareId: subAppDetail?.share_id || sid,
            };

            // Check if the last message is the same as the new message to avoid unnecessary updates
            if (
              lastMessage &&
              lastMessage.text === newMessage.text &&
              lastMessage.loadingText === newMessage.loadingText
            ) {
              return prevMessages;
            }

            if (lastMessage && !lastMessage.isUser) {
              return [...prevMessages.slice(0, -1), newMessage];
            }

            return [
              ...prevMessages,
              {
                thinkList: thinkListcurrentMessageRef.current,

                text: currentMessageRef.current,
                isUser: false,
                loading: false,
                chatId,
                dataId: responseChatId,
                loadingText: message.event,
              },
            ];
          });

          return;
        }

        setIsMuteToggle(Math.random() < 0.5);
        if (isAnswerEvent(message.event) || message.event == SseResponseEventEnum.toolCall) {
          if (message.text) {
            currentMessageRef.current += message.text;
          } else {
            // currentMessageRef.current += '[' + message.tool?.id + ']';
            currentMessageRef.current += `__TOOL_CALL_${message.tool?.id}__` + `\n`;
          }
          setMessages((prevMessages) => {
            const lastMessage = prevMessages[prevMessages.length - 1];
            const newMessage = {
              thinkList: thinkListcurrentMessageRef.current,
              toolJson: lastMessage?.toolJson,
              text: currentMessageRef.current,
              isUser: false,
              loading: true,
              chatId,
              dataId: humanChatId,
              loadingText: message.event,
              appType: appDetail?.appType,
              appName: subAppDetail?.app_name ? subAppDetail?.app_name : appDetail?.app_name,
              appLogo: subAppDetail?.app_logo ? subAppDetail?.app_logo : appDetail?.app_logo,
              appId: subAppDetail?.app_id || id,
              shareId: subAppDetail?.share_id || sid,
            };

            // Check if the last message is the same as the new message to avoid unnecessary updates
            if (
              (lastMessage &&
                lastMessage.text === newMessage.text &&
                lastMessage.loadingText === newMessage.loadingText) ||
              // lastMessage.text.endsWith('[' + message.tool?.id + ']')
              lastMessage.text.endsWith(`__TOOL_CALL_${message.tool?.id}__`)
            ) {
              return prevMessages;
            }

            if (lastMessage && !lastMessage.isUser) {
              return [...prevMessages.slice(0, -1), newMessage];
              // if (prevMessages?.[prevMessages.length - 2]?.interactive) {
              //   return [...prevMessages.slice(0, -2),
              //     {...newMessage,
              //       interactive: prevMessages?.[prevMessages.length - 2]?.interactive,
              //       params: prevMessages?.[prevMessages.length - 2]?.interactive?.params,
              //     }];
              // } else {
              //   return [...prevMessages.slice(0, -1), newMessage];
              // }
            }

            return [
              ...prevMessages,
              {
                thinkList: thinkListcurrentMessageRef.current,
                toolJson: lastMessage?.toolJson,
                text: currentMessageRef.current,
                isUser: false,
                loading: false,
                chatId,
                dataId: responseChatId,
                loadingText: message.event,
              },
            ];
          });
        }

        if (isToolCallEvent(message.event)) {
          setMessages((prevMessages) => {
            const lastMessage = prevMessages[prevMessages.length - 1];
            // 处理 toolJson 合并与 params/response 拼接
            const newToolJson = { ...(lastMessage?.toolJson || {}) };
            const { tool } = message;
            if (tool && tool.id) {
              const prevTool = newToolJson[tool.id] || {};
              // 过滤掉 value 为空的字段
              // 过滤掉 value 为空的字段，修复 TS 报错
              if (tool && typeof tool === 'object') {
                (Object.keys(tool) as Array<keyof typeof tool>).forEach((key) => {
                  if (tool[key] === undefined || tool[key] === null || tool[key] === '') {
                    delete tool[key];
                  }
                });
              }
              newToolJson[tool.id] = {
                ...prevTool,
                ...tool,
                // ...(tool.toolName ? { toolName: tool.toolName } : {}),
                // ...(tool.toolAvatar ? { toolAvatar: tool.toolAvatar } : {}),
                params: (prevTool.params || '') + (tool.params || ''),
                response: (prevTool.response || '') + (tool.response || ''),
              };
            }
            if (lastMessage && !lastMessage.isUser) {
              return [
                ...prevMessages.slice(0, -1),
                {
                  ...lastMessage,
                  toolJson: newToolJson,
                  appType: appDetail?.appType,
                  appName: subAppDetail?.app_name ? subAppDetail?.app_name : appDetail?.app_name,
                  appLogo: subAppDetail?.app_logo ? subAppDetail?.app_logo : appDetail?.app_logo,
                  appId: subAppDetail?.app_id || id,
                  shareId: subAppDetail?.share_id || sid,
                } as Message,
              ];
            }
            return [...prevMessages];
          });
          return;
        }

        if (isInteractiveEvent(message.event)) {
          console.log('interactive', message, message?.interactive);
          setMessages((prevMessages) => {
            const lastMessage = prevMessages[prevMessages.length - 1];
            const { interactive } = message;
            return [
              ...prevMessages.slice(0, -1),
              {
                ...lastMessage,
                interactive,
                params: interactive?.params,
                loading: true,
                appType: appDetail?.appType,
                appName: subAppDetail?.app_name ? subAppDetail?.app_name : appDetail?.app_name,
                appLogo: subAppDetail?.app_logo ? subAppDetail?.app_logo : appDetail?.app_logo,
                appId: subAppDetail?.app_id || id,
                shareId: subAppDetail?.share_id || sid,
              } as Message,
            ];
          });
        }
      },
      variables: { ...variables },
    };
    console.log('variables ', variables);
    setStartChatProps(newStartChatProps);

    try {
      setMessages((prevMessages) => [
        ...prevMessages,
        {
          text: '',
          isUser: false,
          loading: true,
          dataId: humanChatId,
          chatId,
          appType: appDetail?.appType,
          appName: subAppDetail?.app_name ? subAppDetail?.app_name : appDetail?.app_name,
          appLogo: subAppDetail?.app_logo ? subAppDetail?.app_logo : appDetail?.app_logo,
        },
      ]);
      setIsMessageSend(true);
      const responseData = onStartChat
        ? await onStartChat(
            workflowDebug
              ? {
                  ...newStartChatProps,
                  messages:
                    messages.length > 0
                      ? messages.map((item) => ({
                          content: item.text,
                          role: item.isUser ? 'user' : 'assistant',
                          chatId: item.chatId,
                          dataId: item.dataId,
                        }))
                      : commitMessage,
                }
              : newStartChatProps,
          )
        : await startChat(newStartChatProps);
      setMessages((prevMessages) => {
        const updatedMessages = [...prevMessages];
        const lastIndex = updatedMessages.length - 1;
        if (lastIndex >= 0 && updatedMessages[lastIndex].loading) {
          const filteredList = responseData?.responseData || [];
          let quoteList: Quote[] = [];
          if (filteredList.length > 0) {
            quoteList = filteredList.reduce<Quote[]>((acc, item) => {
              return acc.concat(item?.quoteList || []);
            }, []);
          }

          updatedMessages[lastIndex] = {
            ...updatedMessages[lastIndex],
            loading: false,
            chatId,
            dataId: responseChatId,
            quote: quoteList || [],
          };
        }
        return updatedMessages;
      });
    } catch (error) {
      if (error?.status === ResultEnum.UNAUTHORIZED) {
        error?.message && messageApi.info(error?.message);
        resetCookie();
        userStore.getState().actions.clearUserInfoAndToken();
        return;
      }

      setMessages((prevMessages) => [
        ...prevMessages.slice(0, -1),
        {
          thinkList: thinkListcurrentMessageRef.current,
          text: error.message || '对不起，出错了，请稍后再试',
          isUser: false,
          loading: false,
          dataId: humanChatId,
          chatId,
          appType: appDetail?.appType,
          appName: subAppDetail?.app_name ? subAppDetail?.app_name : appDetail?.app_name,
          appLogo: subAppDetail?.app_logo ? subAppDetail?.app_logo : appDetail?.app_logo,
          appId: subAppDetail?.app_id || id,
          shareId: subAppDetail?.share_id || sid,
        },
      ]);
    } finally {
      setIsMessageSend(false);
    }

    if (textAreaRef.current) {
      // console.log(textAreaRef.current)
      textAreaRef.current?.setSelectionRange(0, 0);
      textAreaRef.current?.focus();
    }

    if (isGuessQuestion) {
      setMessages((prevMessages) => {
        if (prevMessages.length > 0) {
          const lastMessage = prevMessages[prevMessages.length - 1];
          console.log('lastMessage', lastMessage);
          if (lastMessage?.text?.includes('换个话题')) {
            setGuessQuestions([]);
            return prevMessages;
          }
          generateGuessQuestions(prevMessages);
        }
        return prevMessages;
      });
    } else {
      setGuessQuestions([]);
    }

    // if (((isInternetSearch && isOnlineMode == true) || isQuote) && chatId) {
    if (chatId) {
      const res = await chatService.updateChat({ chatId }).catch((error) => {
        console.error('更新聊天记录失败:', error);
      });
      if (res?.ai_response && res?.citation_answer && res?.citation_chunks?.length >= 0) {
        setMessages((prevMessages) => {
          const updatedMessages = [...prevMessages];
          updatedMessages[updatedMessages.length - 1] = {
            ...updatedMessages[updatedMessages.length - 1],
            text: updatedMessages[updatedMessages.length - 1]?.text?.replace(
              res?.ai_response,
              res?.citation_answer,
            ),
            // text: res?.citation_answer,
            quote: res?.citation_chunks,
          };
          return updatedMessages;
        });
      }
    }
  };

  useEffect(() => {
    initialMessages.length > 0 && setMessages(initialMessages);
  }, [initialMessages]);

  useEffect(() => {}, []);

  useEffect(() => {
    if (initChatId) {
      setChatId(initChatId);
      setChatNanoId(initChatId);
    }
  }, [initChatId]);

  useEffect(() => {
    if (chatNanoId && !isTest) {
      setChatId(chatNanoId);
      const params = new URLSearchParams(window.location.search);
      params.set('chatId', chatNanoId);
      const newUrl = `${window.location.pathname}?${params.toString()}`;
      router.replace(newUrl);
    }
  }, [chatNanoId]);

  const deleteChatMessage = (chatId: string, dataId: string, appId: string) => {
    if (dataId && chatId && id) {
      chatService.chatDelete(chatId, dataId, appId);
    }
  };

  // 从index开始，删除到下一个 isUser 为 true 的元素（不包括该元素）
  const deleteMessage = (index: number) => {
    setMessages((prevMessages) => {
      const newMessages = [...prevMessages];
      let deleteEnd = index;
      // 找到下一个 isUser 为 true 的元素的下标
      for (let i = index; i < newMessages.length; i++) {
        if (i !== index) {
          if (newMessages[i]?.isUser) {
            break;
          }
        }
        // 删除消息前调用删除接口
        deleteChatMessage(
          newMessages[i]?.dataId || '',
          newMessages[i]?.chatId || '',
          newMessages[i]?.appId || id,
        );
        deleteEnd = i;
      }
      // 删除从index到deleteEnd（不包括第一个 isUser 为 true 的元素）
      newMessages.splice(index, deleteEnd - index + 1);
      return newMessages;
    });
  };

  // 从index开始往回找，找到第一个isUser为true的元素，删除包括该元素及其之后的所有消息，并用该元素的text重新发送
  const reFreshAnswer = (index: number) => {
    if (isMessageSend) {
      messageApi.info('对话正在进行中，请稍后再试！');
      return;
    }
    if (index < 0) return;

    setMessages((prevMessages) => {
      const newMessages = [...prevMessages];
      let userMsgIndex = -1;

      // 从index往前找，找到第一个isUser为true的元素
      for (let i = index; i >= 0; i--) {
        if (newMessages[i]?.isUser) {
          userMsgIndex = i;
          break;
        }
      }

      if (userMsgIndex === -1) {
        // 没有找到用户消息，不做处理
        return newMessages;
      }

      // 删除从userMsgIndex开始到最后的所有消息，并调用删除接口
      for (let i = userMsgIndex; i < newMessages.length; i++) {
        if (newMessages[i]) {
          deleteChatMessage(
            newMessages[i].dataId || '',
            newMessages[i].chatId || '',
            newMessages[i].appId || id,
          );
        }
      }

      thinkListcurrentMessageRef.current = [];

      // 保留userMsgIndex之前的消息
      return newMessages.slice(0, userMsgIndex);
    });

    setTimeout(() => {
      // 重新发送找到的用户消息
      const userMsg = messages.findLast((msg, idx) => idx <= index && msg.isUser);
      if (userMsg?.text) {
        handleSend(userMsg.text);
      }
    }, 10);
  };

  const changeInputType = () => {
    setVoice(!voice);
  };

  const onVoiceStop = (text: string) => {
    setMessages((prevMessages) => {
      const lastMessage = prevMessages?.[prevMessages.length - 1];
      if (lastMessage && lastMessage.text === '语音识别中') {
        const newMessages = [...prevMessages];
        newMessages.pop();
        return newMessages;
      }
      return prevMessages;
    });
    if (isMessageSend) {
      handleInterrupt();
    }
    handleSend(text);
  };

  const textGenerateMsgAdd = () => {
    setMessages((prevMessages) => {
      const lastMessage = prevMessages?.[prevMessages.length - 1];
      if (lastMessage && lastMessage.isTextGenerate) {
        return prevMessages;
      }
      return [
        ...prevMessages,
        { text: '语音识别中', isUser: true, loading: true, isTextGenerate: true },
      ];
    });
  };

  const textGenerateMsgRemove = () => {
    setMessages((prevMessages) => {
      const lastMessage = prevMessages?.[prevMessages.length - 1];
      if (lastMessage && lastMessage.isTextGenerate) {
        const newMessages = [...prevMessages];
        newMessages.pop();
        return newMessages;
      }
      return prevMessages;
    });
  };

  const onSTT = (status: number) => {
    if (status == 0) {
      setIsMessageSend(true);
      setIsTextGenerate(true);
      textGenerateMsgAdd();
    }
    if (status == 1) {
      setIsMessageSend(true);
      setIsTextGenerate(false);
      textGenerateMsgRemove();
    }
    if (status == 2) {
      setIsMessageSend(false);
      setIsTextGenerate(false);
      textGenerateMsgRemove();
    }
  };

  useEffect(() => {
    if (isTextGenerate) {
      textGenerateMsgAdd();
    } else {
      textGenerateMsgRemove();
    }
  }, [isTextGenerate]);

  const onInterrupt = () => {
    if (isTextGenerate) {
      setIsTextGenerate(false);
      setIsMessageSend(false);
    } else {
    }
    handleInterrupt();
  };

  event$?.useSubscription((val) => {
    if (val.type === ChatEventType.SENDTEXT) {
      handleSend(val.data.toString());
    }
  });

  const handleQuestionClick = (question: string) => {
    if (question) {
      // 直接发送用户点击的问题
      handleSend(question);
    }
  };

  useEffect(() => {
    if (!voiceEnabled && voice) {
      setVoice(false);
    }
  }, [voiceEnabled]);

  const userInputVariables = useMemo(() => {
    if (subAppDetail?.variables || subAppDetail?.workflow?.chatConfig?.variables) {
      const subAppVariables =
        subAppDetail?.variables?.length > 0
          ? subAppDetail?.variables
          : subAppDetail?.workflow?.chatConfig?.variables;
      const subAppVariablesFliter = subAppVariables?.filter(
        (item: any) => item?.type !== VariableInputEnum.custom,
      );
      return subAppVariablesFliter || userSelectVariables;
    }
    return (
      workflow?.chatConfig?.variables?.filter((item) => item.type !== VariableInputEnum.custom) ||
      userSelectVariables
    );
  }, [workflow, userSelectVariables, subAppDetail]);

  const [chatStart, setChatStart] = useState(true);
  const chatStarted =
    chatStart || userInputVariables?.length === 0 || userInputVariables?.length === undefined;

  const isWebRTCSopport = useMemo(() => {
    return typeof window !== 'undefined' && typeof window.RTCPeerConnection !== 'undefined';
  }, []);

  const isMetahumanEnabled = useMemo(() => {
    return virtualAvatarEnabled && permissionConfig?.metahumanQuota && isWebRTCSopport;
  }, [virtualAvatarEnabled, permissionConfig, isWebRTCSopport]);

  return (
    <div className={`flex h-full flex-col ${!isPc ? 'm-0 w-full' : 'mx-auto w-full items-center'}`}>
      {contextHolder}
      {isMetahumanEnabled ? (
        <MetaMessageList
          messages={messages}
          isMessageSend={isMessageSend}
          deleteMessage={(index) => deleteMessage(index)}
          reFreshAnswer={(index) => reFreshAnswer(index)}
          handleSend={handleSend}
          guessQuestions={guessQuestions}
          onQuestionClick={handleQuestionClick}
          workflowDebug={workflowDebug}
        />
      ) : (
        <MessageList
          messages={messages}
          isMessageSend={isMessageSend}
          deleteMessage={(index) => deleteMessage(index)}
          reFreshAnswer={(index) => reFreshAnswer(index)}
          handleSend={handleSend}
          guessQuestions={guessQuestions}
          onQuestionClick={handleQuestionClick}
          workflowDebug={workflowDebug}
        />
      )}
      <div
        style={isPc ? {} : {}}
        className={`flex w-full flex-col items-center justify-center rounded-[12px] border-none ${
          !isPc
            ? 'fixed bottom-0 left-0 right-0 z-[600] bg-white p-2'
            : 'mx-auto w-full max-w-[800px]'
        }`}
      >
        <div className="relative flex w-full items-center rounded-2xl">
          <MessageSendInputHome
            handleSend={handleSend}
            changeInputType={changeInputType}
            handleInterrupt={handleInterrupt}
            isMessageSend={isMessageSend}
            isHome={false}
            voice={voice}
            onInterrupt={onInterrupt}
            onVoiceStop={onVoiceStop}
            onSTT={onSTT}
          />
        </div>
      </div>
    </div>
  );
};

export default ChatBox;
